package com.lsyonlygoddes.controller;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.FileInputStream;
import java.net.URLEncoder;

/**
 * @author:lsyonlygoddes
 * @time:2023/11/23 13:06
 */
@CrossOrigin
@RestController
public class DownloadController {
    @GetMapping("/download")
    public ResponseEntity<byte[]> download(@RequestParam("parentPath") String parentPath, @RequestParam("fileName") String fileName) throws Exception {
        // 以下载G：/test1.txt 文件为例
//        FileInputStream is = new FileInputStream("G:/test1.txt");
        FileInputStream is = new FileInputStream(parentPath + "/" + fileName);
        byte[] bytes = new byte[is.available()];
        // 一次读取bytes.length个字节 并将读到的字节放入bytes数组中
        is.read(bytes);
        is.close();
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName,"UTF-8"));
        // 将要下载的文件的字节流返回给浏览器
        ResponseEntity res = new ResponseEntity<byte[]>(bytes, httpHeaders, HttpStatus.OK);
        return res;
    }
}
